import { User } from './../models';
import { paraMap, paramMapByArr } from './../utils';

export default {
    addUser(param: object|any) {
        const user: any = new User();
        paraMap(param, user);
        return user.save();
    },
    findOne(param: object|any) {
        return User.findOne(param);
    },
    findOneAndUpdate(filter: object | any, update: object | any) {
        return User.findOneAndUpdate(filter, update, { new: true });
    },
    findById(id: string) {
        return User.findById(id);
    },
    find(param: object | any): Promise<any> {
        const _para: any = paramMapByArr(param, ['role_id', 'user_name', 'status', 'tel', 'qq', 'wechart', 'professional_class', 'credit_rating']);
        // return User.find(_para).limit(param.page_size).skip(param.page_no - 1);
        return User.aggregate([
            {
                $match: _para
            },
            {
                $limit: param.page_size
            },
            {
                $skip: param.page_no - 1
            },
            {
                $project: {
                    id: '$_id',
                    _id: '$-',
                    user_name: '$user_name',
                    login_ip: '$login_ip',
                    user_avatar: '$user_avatar',
                    message_stacks: '$message_stacks',
                    status: '$status',
                    tel: '$tel',
                    qq: '$qq',
                    wechart: '$wechart',
                    professional_class: '$professional_class',
                    credit_rating: '$credit_rating',
                    memo: '$memo',
                    create_at: '$create_at',
                    update_at: '$update_at'
                }
            }
        ]).exec();
    },
    updateUserRoleId(param: object | any) {
        return User.update({ _id: param.user_id }, { role_id: param.role_id });
    }
};